/**
 * created  on 15/11/2017.
 */




window.addEventListener("load", function () {
    HttpPermitManageMain.init();
});

/**
 * 整个脚本的初始化入口
 *
 */
const HttpPermitManageMain = {


    init: function () {
        HttpPermitSearchBox.init();
        HttpPermitTableBox.init();
    }
};

const HttpPermitSearchBox = {

    box: null,

    form: null,


    _prefixSpan_: null,
    /**
     * 嵌入搜索框的按钮,用于改变搜索类型
     */
    _searchFieldBtn_: null,

    init: function () {
        this.box = document.querySelector("div.box.permissionSearch");
        this.form = this.box.querySelector("form.permissionSearchForm");
        this._searchFieldBtn_ = this.form.querySelector("button.btn.search-btn");
        this._prefixSpan_ = this.form.querySelector("span.permit-prefix");

        //事件监听器
        this.form.querySelector("select.type-select").addEventListener("change", function (event) {
            HttpPermitSearchBox.typeChangeEventHandler(event);
        });

        this.form.querySelector("button.btn.search-btn").addEventListener("click", function () {
            HttpPermitSearchBox.search();
        });

        this.form.querySelector("input.search-key").addEventListener("keydown", function (event) {
            let keyCode = 13;
            if (event.which == keyCode || event.keyCode == keyCode) {
                HttpPermitSearchBox.search();
            }
        });

    },
    search: function () {
        let select, input, value;
        select = this.form.querySelector("select.type-select");
        input = this.form.querySelector("input.search-key");
        let params;
        params = new Params();

        if (select.value) {
            params.permit = select.value + ":";
        } else {
            params.permit = "";
        }

        value = input.value.trim();
        if (value) {
            params.permit += input.value;
        }

        // 刷新 table
        HttpPermitTableBox.refresh(this.form.action, params);

    }, typeChangeEventHandler: function (event) {
        let select;
        select = event.target;
        if (select.value) {
            this._prefixSpan_.innerHTML = select.value + ":";
        } else {
            this._prefixSpan_.innerHTML = "";
        }

    }, getForm: function () {
        return this.form;
    }


};

/**
 * 负责 Table 的显示逻辑
 */
const HttpPermitTableBox = {


    _url_: null,

    _tableBox_: null,

    _params_: null,

    _overlayDiv_: null,

    _draw_: 0,

    _dataTable_: null,

    /**
     * 表的编辑按钮数组
     * @see HttpPermitTableEventHandler#_decisionButtonVisible_
     */
    _button_: [
        {
            className: "btn btn-danger Del disabled leastOne",
            text: "删除",
            action: function (e, dt, node, config) {
                HttpPermitTableEventHandler.buttonDelete(e, dt, node, config);
            }
        }, {
            className: "btn btn-primary Edit disabled onlyOne",
            text: "编辑",
            action: function (e, dt, node, config) {
                HttpPermitTableEventHandler.buttonEdit(e, dt, node, config);
            }
        }, {
            className: "btn btn-primary Add",
            text: "添加",
            action: function (e, dt, node, config) {
                HttpPermitTableEventHandler.buttonAdd(e, dt, node, config);
            }
        },
        {
            className: "btn btn-primary Grant disabled onlyOne",
            text: "授权",
            titleAttr: "也可点击行的序号",
            action: function (e, dt, node, config) {
                HttpPermitTableEventHandler.buttonGrant(e, dt, node, config);
            }
        }
    ],


    _language_: {
        processing: "飞速加载中",
        emptyTable: "没有搜索到符合的结果",
        zeroRecord: "没有匹配的结果",
        paginate: {
            first: "首页",
            last: "尾页",
            previous: "上一页",
            next: "下一页"
        },
        select: {
            rows: "%d 行已选择"
        },
        info: "显示 _START_ 至 _END_   共 _TOTAL_ 行",
        lengthMenu: "每页显示 _MENU_ 行",
        search: "过滤:"
    },

    _createButton_: {
        // className: "btn btn-primary Add",
        text: "添加",
        action: function (e, dt, node, config) {
            HttpPermitTableEventHandler.buttonAdd(e, dt, node, config);
        }
    },

    _updateButton_: {
        className: "btn btn-primary Edit disabled onlyOne",
        text: "编辑",
        action: function (e, dt, node, config) {
            HttpPermitTableEventHandler.buttonEdit(e, dt, node, config);
        }
    },

    _deleteButton_: {
        className: "btn btn-danger Del disabled onlyOne",
        text: "删除",
        action: function (e, dt, node, config) {
            HttpPermitTableEventHandler.buttonDelete(e, dt, node, config);
        }
    },

    _grantButton_: {
        className: "btn btn-primary grant disabled onlyOne",
        text: "授权",
        action: function (e, dt, node, config) {
            HttpPermitTableEventHandler.buttonGrant(e, dt, node, config);
        }
    },

    _resetPasswordButton_: {
        className: "btn btn-primary grant disabled onlyOne",
        text: "重置密码",
        action: function (e, dt, node, config) {
            HttpPermitTableEventHandler.resetPassword(e, dt, node, config);
        }
    },

    _columns_: [
        {
            "searchable": false,
            title: "序号",
            "className": "row-num text-nowrap text-center",
            "data": function (row, type, val, meta) {
                let cellData;
                switch (type) {
                    case 'display':
                        cellData = parseInt(meta.row) + 1;
                        break;
                    case 'set':
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "rowNum",
            "orderable": false,
            "type": "num"
        },
        {
            "searchable": false,
            title: "ID",
            "className": "id text-nowrap text-center",
            "data": function (row, type, val, meta) {
                let cellData;
                switch (type) {
                    case 'display':
                        cellData = row.id;
                        break;
                    case 'set':
                        row.id = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "id",
            "orderable": false,
            "type": "num"

        },
        {
            "searchable": false,
            title: "name",
            "className": "permit text-nowrap text-center",
            "data": function (row, type, val, meta) {
                let cellData;
                switch (type) {
                    case 'display':
                        cellData = row.name == "" ? "--" : row.name;
                        break;
                    case 'set':
                        row.name = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "name",
            "orderable": false,
            "type": "string"
        },
        {
            "searchable": false,
            title: "手机号",
            "className": "desc text-nowrap text-center",
            "data": function (row, type, val, meta) {
                let cellData;
                switch (type) {
                    case 'display':
                        cellData = row.desc;
                        break;
                    case 'set':
                        row.desc = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "desc",
            "orderable": false,
            "type": "string"

        },
        {
            "searchable": false,
            title: "创建时间",
            "className": "crate-time text-nowrap text-center",
            "data": function (row, type, val, meta) {
                let cellData;
                switch (type) {
                    case 'display':
                        cellData = row.createTime;
                        break;
                    case 'set':
                        row.createTime = val;
                        break;
                    case'filter':
                    default :
                }
                return cellData;
            },
            "defaultContent": "--",
            "name": "createTime",
            "orderable": false,
            "type": "string"

        }
    ],


    init: function () {
        this._tableBox_ = document.querySelector("div.box.table-box");

        this._searchIfUserNoAction_();
    },
    _searchIfUserNoAction_: function () {
        let task = null, _this;
        _this = this;
        let callBack = function () {
            if (!_this._dataTable_) {
                _this.refresh(
                    HttpPermitSearchBox.getForm().action
                    , new Params()
                );
            }

            if (task) {
                window.clearTimeout(task);
            }
        };

        task = window.setTimeout(callBack, 2000);
    },
    /**
     * 第一次搜索时由 refresh 调用.
     * 完成成以下功能:
     * 1.初始化 table
     * 2.初始化 table 事件处理器
     */
    initDataTable: function () {
        let _this;
        _this = this;
        $.fn.dataTable.ext.errMode = 'none';

        let settings = this._getSetting_();
        this._dataTable_ = $("#permissionManageTable").DataTable(settings);


        this._dataTable_.on("xhr.dt", function (e, settings, json, xhr) {
            _this._convertJson_(json)
        });
        /*  this._dataTable_.on("select", function (e, dt, type, indexes) {
         HttpPermitTableEventHandler.select(e, dt, type, indexes);
         });
         this._dataTable_.on("deselect", function (e, dt, type, indexes) {
         HttpPermitTableEventHandler.deselect(e, dt, type, indexes);
         });*/

        HttpPermitAddEditor.init();
        HttpPermitTableEventHandler.init(this._dataTable_);
    },
    /**
     * 返回 data table 的配置
     ** @private
     */
    _getSetting_: function () {
        return {
            serverSide: true,
            info: true,
            dom: 'lBrtip',
            scrollX: true,
            /* scrollY: "50vh",*/
            autoWidth: false,
            searching: false,
            columns: this._columns_,
            language: this._language_,
            rowId: "id",
            processing: true,
            scrollCollapse: true,
            buttons: this._getVisibleButton_(),
            keys: false,
            select: true,
            pagingType: "full_numbers",
            ordering: false,
            ajax: {
                url: this._url_,
                data: function (data, settings) {
                    HttpPermitTableBox._data_(data, settings);
                },
                dataSrc: "data.data"
            }
        };
    },
    /**
     *
     * 将服务器返回的 json 进行转换以便 data table 能够显示.
     * 此方法由 DataTable 的  xhr.dt 事件处理器调用.
     * @param jsonResult 要被转换的 json 对象
     * @private
     */
    _convertJson_: function (jsonResult) {
        if (jsonResult.code === "ok") {
            jsonResult.recordsTotal = jsonResult.data.recordsTotal;
            jsonResult.recordsFiltered = jsonResult.data.recordsFiltered;
        }
    },
    /**
     *根据用户拥有的许可返回相应的按钮
     * @private
     */
    _getVisibleButton_: function () {
        let buttons;
        buttons = [];
        // if (AdminHasRoot) {
        //     buttons.push(this._deleteButton_);
        // }
        // if (ADMIN_HAS_UPDATE_PERMISSION) {
        //     buttons.push(this._updateButton_);
        // }
        //
        // if (ADMIN_HAS_CREATE_PERMISSION) {
        //     buttons.push(this._createButton_);
        // }
        // if (AdminHasRoot) {
        //     buttons.push(this._grantButton_);
        //     buttons.push(this._resetPasswordButton_);
        // }
        buttons.push(this._createButton_);
        return buttons;
    },
    /**
     * 处理发送至服务器的 参数 .
     * 此方法由 DataTable 调用
     * @param data
     * @param settings
     * @private
     */
    _data_: function (data, settings) {
        let first, max;
        for (let key in data) {
            switch (key) {
                case "start":
                    first = data[key];
                    break;
                case "length":
                    max = data[key];
                    break;
                case "":
            }
            delete data[key];
        }
        data.page = first / max + 1;
        data.rows = max;
        $.extend(data, this._params_);
    },
    /**
     * 当 用户点击搜索按钮时调用此方法刷新 table
     * @param url
     * @param params
     */
    refresh: function (url, params) {
        // 先执行
        this._url_ = url;
        this._params_ = params;
        if (!this._dataTable_) {
            this.initDataTable();
        } else {
            this._dataTable_.ajax.url(this._url_).load();
        }
        this.showTableBox();
    },
    showTableBox: function () {
        if (this._tableBox_.classList.contains("hidden")) {
            this._tableBox_.classList.remove("hidden");
        }
    },
    hideTableBox: function () {
        if (!this._tableBox_.classList.contains("hidden")) {
            this._tableBox_.classList.add("hidden");
        }
    },
    getDataTable: function () {
        return this._dataTable_;
    }


};

const HttpPermitTableEventHandler = {

    _dataTable_: null,

    _tableBox_: null,

    _table_: null,

    /**
     *
     * 在 data table 初始化后调用
     * @param dataTable
     */
    init: function (dataTable) {
        let _this;
        this._dataTable_ = dataTable;
        this._tableBox_ = document.querySelector("div.box.table-box");
        this._table_ = this._tableBox_.querySelector("#permissionManageTable");
        _this = this;
        // this._table_.addEventListener("keydown", function (event) {
        //     _this.deleteKey(event);
        // });
    },
    buttonGrant: function (e, dt, node, config) {
        RoleOfAdminEditor.dialogEditor(dt.row({selected: true}).data());
    },
    buttonAdd: function (e, dt, node, config) {
        HttpPermitAddEditor.dialogEditor(dt);
    },
    resetPassword: function (e, dt, node, config) {
        AdminPasswordEditor.dialog(dt.row({selected: true}).data().id);
    },
    buttonDelete: function (e, dt, node, config) {
        let rowDatas;
        rowDatas = dt.rows({selected: true}).data();
        if (rowDatas.length != 1) {
            return;
        }
        //
        this._doDel_(rowDatas);
    },
    deleteKey: function (event) {
        if (event.which == 46 || event.keyCode == 46) {
            let rowDatas = this._dataTable_.rows({selected: true}).data();
            if (rowDatas.length != 1) {
                return;
            }
            this._doDel_(rowDatas);
        }
    },
    _doDel_: function (rowDatas) {
        let params, callBack, _this;
        params = new Params();
        params["adminId"] = rowDatas[0].id;
        _this = this;
        callBack = function (data) {
            if (data.status === true) {
                $.notify({
                    icon: 'glyphicon glyphicon-leaf',
                    title: "通知",
                    message: data.message
                }, {
                    type: "success",
                    mouse_over: "pause",
                    delay: 3000,
                    placement: {
                        align: "center"
                    },
                    animate: {
                        enter: "animated",
                        exit: "animated"
                    }
                });
                // 刷新当前页
                _this._dataTable_.ajax.reload(null, false);
            } else {
                BootstrapDialog.alert({
                    title: '错误',
                    message: data.message,
                    type: BootstrapDialog.TYPE_DANGER,
                    closable: true,
                    draggable: true,
                    buttonLabel: '确认',
                });
            }
        };
        BootstrapDialog.confirm({
            title: '警告',
            message: "确定要删除管理员 [ id=" + rowDatas[0].id + "] 吗?",
            type: BootstrapDialog.TYPE_WARNING,
            closable: true,
            draggable: true,
            btnCancelLabel: '取消',
            btnOKLabel: '确认',
            btnOKClass: 'btn-warning',
            callback: function (result) {
                if (result) {
                    $.post(RoamCloudManage.userPath + "/deleteAdmin", params, callBack, "json");
                }
            }
        });
    },
    buttonEdit: function (e, dt, node, config) {
        HttpPermitAddEditor.dialogEditor(dt, "edit")
    },
    select: function (e, dt, type, indexes) {
        DataTableUtils.decisionButtonVisible(dt);

    },
    deselect: function (e, dt, type, indexes) {
        DataTableUtils.decisionButtonVisible(dt);
    }

};

const HttpPermitAddEditor = {

    _dialogDiv_: null,

    _dialogEditor_: null,

    _form_: null,

    _permitPrefixSpan_: null,

    /**
     * 在 data table 初始化后调用
     */
    init: function () {
        this._dialogDiv_ = document.querySelector("#permissionEditDialog");
        this._form_ = this._dialogDiv_.querySelector("form.permit-edit");
        this._permitPrefixSpan_ = this._form_.querySelector("span.permit-prefix");
    },
    _initDialogEditor_: function () {
        let _this, e;
        _this = this;

        this._dialogEditor_ = $("#permissionEditDialog").modal({
            show: false,
            keyboard: true,
            backdrop: "static"
        });
        // 提交按钮
        e = this._dialogDiv_.querySelector("#editorFormSubmit");
        e.addEventListener("click", function () {
            _this.save();
        });

        // 事件监听器
        this._form_.querySelector("select.permit-type").addEventListener("change", function (event) {
            _this.typeChangeEventHandler(event);
        });
    },
    typeChangeEventHandler: function (event) {
        let select;
        select = event.target;
        this._permitPrefixSpan_.innerHTML = select.value + ":";
    },

    /**
     *
     * @param dt dataTable 对象
     * @param type [add,edtit]
     */
    dialogEditor: function (dt) {
        if (!this._dialogEditor_) {
            this._initDialogEditor_();
        }
        FormUtils.formInBoxDisabled(this._dialogDiv_, this._form_, false);
        this._initForAdd_(dt);
        this._showDialog_(true);
    },
    _initForAdd_: function (dt) {
        this._dialogDiv_.querySelector(".modal-title").innerHTML = "添加 Http 权限";
        //后 reset
        this._form_.reset();
    },

    save: function () {
        FormUtils.formInBoxDisabled(this._dialogDiv_, this._form_, true);

        let input, select, params, callBack, _this;

        input = this._form_.permit;
        select = this._form_.permitTypeEditor;

        params = new Params();

        params.permit = select.value + ":" + input.value.trim();
        params.desc = this._form_.desc.value.trim();

        _this = this;
        callBack = function (json) {
            _this._saveCallBack_(json);
        };

        $.post(this._form_.action, params, callBack, "json");

    },
    _saveCallBack_: function (json) {
        this._showDialog_(false);
        FormUtils.formInBoxDisabled(this._dialogDiv_, this._form_, false);

        if (json.code === "ok") {

            this._showAddSuccess_(this._getAddSuccessMsg_(json));
            //刷新本页
            HttpPermitTableBox.getDataTable().draw(false);
        } else {

            this._showAddFailure_(this._getAddFailureMsg_(json));
        }

    },
    _showDialog_: function (show) {
        if (show) {
            this._dialogEditor_.modal("show");
        } else {
            this._dialogEditor_.modal("hide");
        }

    },
    _getAddFailureMsg_: function (json) {
        let message;
        message = json.msg;
        if (json.data) {
            message += "<br/>";
            for (var key in json.data) {
                message += key + " : " + json.data[key];
                message += "<br/>";
            }
        }
        return message;
    },
    _getAddSuccessMsg_: function (json) {
        let message;
        message = json.message + '(已刷新本页),<strong class="text-danger">新数据 不一定显示在本页</strong>' + '<br/>';
        message += "已添加 Http 权限 : " + json.data.permit;
        return message;
    },
    _showAddSuccess_: function (message) {
        $.notify({
            icon: 'glyphicon glyphicon-leaf',
            title: "通知",
            message: message
        }, {
            type: "success",
            mouse_over: "pause",
            delay: 3000,
            placement: {
                align: "center"
            },
            animate: {
                enter: "animated",
                exit: "animated"
            }
        });
    },
    _showAddFailure_: function (message) {
        BootstrapDialog.alert({
            title: '错误',
            message: message,
            type: BootstrapDialog.TYPE_DANGER,
            closable: true,
            draggable: true,
            buttonLabel: '确认',
        });
    }
};

